package com.yjt.fresh.activity;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.HttpManager;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.listener.HttpOnNextListener;
import com.yjt.fresh.AuthResult;
import com.yjt.fresh.PayResult;
import com.yjt.fresh.R;
import com.yjt.fresh.api.ApiBuyCardAliPay;
import com.yjt.fresh.api.ApiBuyCardWeiXinPay;
import com.yjt.fresh.api.ApiGetRechargeCardList;
import com.yjt.fresh.base.BaseSimpleActivity;
import com.yjt.fresh.bean.BeanBuyCard;
import com.yjt.fresh.bean.BeanWeiXinResult;
import com.yjt.fresh.utils.PreferenceManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AtyBuyCard extends BaseSimpleActivity {
    private static final int ALI_PAY = 1006;
    private static final int WEI_XIN_PAY = 1007;
    @BindView(R.id.back)
    RelativeLayout mBack;
    @BindView(R.id.ivAppAtyBuyCardCard)
    ImageView mIvCard;
    @BindView(R.id.tvAppAtyBuyCardPerMoney)
    TextView mTvPerMoney;
    @BindView(R.id.llAppAtyBuyCardChooseCard)
    LinearLayout mLlChooseCard;
    @BindView(R.id.ivAppAtyBuyCardSub)
    ImageView mIvSub;
    @BindView(R.id.tvAppAtyBuyCardCount)
    TextView mTvCount;
    @BindView(R.id.ivAppAtyBuyCardAdd)
    ImageView mIvAdd;
    @BindView(R.id.llAppAtyApplyBackCount)
    LinearLayout mLlCount;
    @BindView(R.id.tvAppAtyBuyCardMoney)
    TextView mTvMoney;

    @BindView(R.id.ivAppAtyBuyCardWeiXinPay)
    ImageView mIvWeiXinPay;
    @BindView(R.id.llAppAtyBuyCardWeiXinPay)
    LinearLayout mLlWeiXinPay;
    @BindView(R.id.ivAppAtyBuyCardAli)
    ImageView mIvAli;
    @BindView(R.id.llAppAtyBuyCardAliPay)
    LinearLayout mLlAliPay;
    @BindView(R.id.tvAppAtyBuyCardToPay)
    TextView mTvToPay;
    private List<String> mMoneyList;
    private List<BeanBuyCard> mBeanBuyCards;
    private int mCardCount = 1;
    private String mPerMoney;
    private String mChargeCardID;
    private int mPayWay;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private BeanWeiXinResult mWeiXinResult;
    private IWXAPI iwxapi;

    @Override
    protected int getContentView() {
        return R.layout.app_aty_buy_card;
    }

    @Override
    protected void initViews() {
        ButterKnife.bind(this);
    }

    @Override
    protected void initEvent() {
        getData();
        initClick();
    }

    private void initClick() {
        mLlChooseCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPicker(mMoneyList,"选择面额" );
            }
        });

        mIvAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCardCount ++;
                mTvCount.setText(mCardCount+"");
                mTvMoney.setText((mCardCount*Double.valueOf(mPerMoney))+"");
            }
        });

        mIvSub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCardCount > 1){
                    mCardCount --;
                    mTvCount.setText(mCardCount+"");
                    mTvMoney.setText((mCardCount*Double.valueOf(mPerMoney))+"");
                }
            }
        });

        mLlAliPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = ALI_PAY;
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_02);
                mIvAli.setImageResource(R.mipmap.a2_icon_01);
            }
        });

        mLlWeiXinPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPayWay = WEI_XIN_PAY;
                mIvWeiXinPay.setImageResource(R.mipmap.a2_icon_01);
                mIvAli.setImageResource(R.mipmap.a2_icon_02);
            }
        });

        mTvToPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (mPayWay) {
                    case ALI_PAY:
                        aliPay();
                        break;
                    case WEI_XIN_PAY:
                        weiXinPay();
                        break;
                }
            }
        });
        mBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        int wxPayResult = PreferenceManager.getInstance().getWXPayResult();
        if (wxPayResult != 110) {
            if (wxPayResult == 0) {
                //微信支付成功
                Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                //微信支付失败
                Toast.makeText(mContext, "支付未成功", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void weiXinPay() {
        ApiBuyCardWeiXinPay apiBuyCardWeiXinPay = new ApiBuyCardWeiXinPay(new HttpOnNextListener<BeanWeiXinResult>() {

            @Override
            public void onNext(BeanWeiXinResult beanWeiXinResult) {
                mWeiXinResult = beanWeiXinResult;
                toWXPay();
            }

            @Override
            public void onReLogin() {
                toLogin();
            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("CHARGECARD_ID", mChargeCardID);
        map.put("NUM", mCardCount);
        apiBuyCardWeiXinPay.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiBuyCardWeiXinPay);
    }

    private void toWXPay() {
        iwxapi = WXAPIFactory.createWXAPI(this, null); //初始化微信api
        iwxapi.registerApp(mWeiXinResult.getAppid()); //注册appid  appid可以在开发平台获取

        Runnable payRunnable = new Runnable() {  //这里注意要放在子线程
            @Override
            public void run() {
                PayReq request = new PayReq(); //调起微信APP的对象
                //下面是设置必要的参数，也就是前面说的参数,这几个参数从何而来请看上面说明
                request.appId = mWeiXinResult.getAppid();
                request.partnerId = mWeiXinResult.getPartnerid();
                request.prepayId = mWeiXinResult.getPrepayid();
                request.packageValue = "Sign=WXPay";
                request.nonceStr = mWeiXinResult.getNoncestr();
                request.timeStamp = mWeiXinResult.getTimestamp();
                request.sign = mWeiXinResult.getSign();
                iwxapi.sendReq(request);//发送调起微信的请求
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private void aliPay() {
        ApiBuyCardAliPay apiBuyCardAliPay = new ApiBuyCardAliPay(new HttpOnNextListener<String>() {


            @Override
            public void onNext(String s) {
                payV2(s);
            }

            @Override
            public void onReLogin() {
                toLogin();
            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        map.put("CHARGECARD_ID", mChargeCardID);
        map.put("NUM", mCardCount);
        apiBuyCardAliPay.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiBuyCardAliPay);
    }

    /**
     * 支付宝支付业务
     */
    public void payV2(final String orderInfo) {
        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(AtyBuyCard.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private void getData() {
        ApiGetRechargeCardList apiGetRechargeCardList = new ApiGetRechargeCardList(new HttpOnNextListener<List<BeanBuyCard>>() {
            @Override
            public void onNext(List<BeanBuyCard> beanBuyCards) {
                mChargeCardID = beanBuyCards.get(0).getCHARGECARD_ID();
                mMoneyList = new ArrayList<>();
                mBeanBuyCards = beanBuyCards;
                for (int i = 0; i < mBeanBuyCards.size(); i++) {
                    mMoneyList.add(beanBuyCards.get(i).getMONEY());
                }
                Glide.with(mIvCard.getContext()).load(beanBuyCards.get(0).getIMG()).placeholder(R.mipmap.image_default).into(mIvCard);
                mTvPerMoney.setText(beanBuyCards.get(0).getMONEY());
                mTvCount.setText(mCardCount+"");
                mTvMoney.setText((mCardCount*Double.valueOf(beanBuyCards.get(0).getMONEY()))+"");
            }

            @Override
            public void onReLogin() {

            }
        },mContext,true,false,false);
        Map<String,Object> map = new HashMap<>();
        map.put("SESSION_ID", PreferenceManager.getInstance().getUserInfo().getSESSION_ID());
        apiGetRechargeCardList.setMap(map);
        HttpManager.getInstance().doHttpDeal(apiGetRechargeCardList);
    }

    private void showPicker(final List<String> list, String title) {
        OptionsPickerView<String> optionsPickerView = new OptionsPickerBuilder(mContext, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                mPerMoney = mBeanBuyCards.get(options1).getMONEY();
                mTvPerMoney.setText(mPerMoney);
                Glide.with(mIvCard.getContext()).load(mBeanBuyCards.get(options1).getIMG()).placeholder(R.mipmap.image_default).into(mIvCard);
                mTvCount.setText(mCardCount+"");
                mTvMoney.setText((mCardCount*Double.valueOf(mPerMoney))+"");
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {

            }
        })
                .setSubmitText("确定")//确定按钮文字
                .setCancelText("取消")//取消按钮文字
                .setTitleText(title)//标题
                .setSubCalSize(15)//确定和取消文字大小
                .setTitleSize(18)//标题文字大小
                .setTitleColor(getResources().getColor(R.color.color_333333))//标题文字颜色
                .setSubmitColor(getResources().getColor(R.color.color_43b624))//确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.color_CCCCCC))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))//标题背景颜色 Night mode
                .setBgColor(getResources().getColor(R.color.white))//滚轮背景颜色 Night mode
                .setContentTextSize(15)//滚轮文字大小
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setCyclic(false, false, false)//循环与否
                .setSelectOptions(1, 1, 1)  //设置默认选中项
                .setOutSideCancelable(true)//点击外部dismiss default true
                .isDialog(false)//是否显示为对话框样式
                .isRestoreItem(false)//切换时是否还原，设置默认选中第一项。
                .build();

        optionsPickerView.setPicker(list);
        optionsPickerView.show();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if ("9000".equals(resultStatus)) {
                        Toast.makeText(mContext, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        Toast.makeText(mContext, "支付未成功", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档

                    break;
                }
                default:
                    break;
            }
        }
    };

}
